package com.aiatomic.couting.account;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.AccountInfoActivity;
import com.aiatomic.couting.ICodeMsg;
import com.aiatomic.couting.IConstant;
import com.aiatomic.couting.LoginActivity;
import com.aiatomic.couting.R;
import com.aiatomic.couting.models.OrderEntity;
import com.aiatomic.couting.util.AppUtils;
import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.widgets.LoadingDialog;
import com.aiatomic.couting.widgets.OrderAdapter;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class FragmentAccountInfoOrders extends Fragment {
	private View view;
	private ListView listview_orders;
	private OrderAdapter adapter;
	private AccountInfoActivity activity;
	private LoadingDialog dialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_account_info_orders, container, false);
		activity = (AccountInfoActivity) getActivity();
		dialog = new LoadingDialog(getActivity());
		listview_orders = (ListView) view.findViewById(R.id.listview_orders);
		List<OrderEntity> objects = new ArrayList<OrderEntity>();
		adapter = new OrderAdapter(activity, R.layout.custom_order_list_item, objects);
		listview_orders.setAdapter(adapter);
		bindEvent();
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		check_orders();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
	}

	private void bindEvent() {
		listview_orders.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				FragmentAccountInfoOrdersDetails fragment = new FragmentAccountInfoOrdersDetails(adapter.getItem(position));
				activity.addFragment(fragment);
			}
		});		
	}
	private void initUI(JSONArray orders) {
		adapter.clear();
		for (int i = 0; i < orders.length(); i++) {
			try {
				JSONObject json = orders.getJSONObject(i);
				OrderEntity entity = new OrderEntity();
				entity.setGood_id(json.getString("product_id"));
				entity.setDiscout(json.getDouble("discount"));
				entity.setGm_user_id(json.getString("gm_account_id"));
				entity.setGm_user_name(json.getString("gm_user_name"));
				entity.setPrice(json.getDouble("price"));
				entity.setGm_order_id(json.getString("gm_order_id"));
				Calendar ctime=Calendar.getInstance();
				ctime.setTimeInMillis(json.getLong("create_time")*1000);
				entity.setCreated_time_loc(ctime.getTime());
				entity.setReal_give_days(json.getInt("real_give"));
				Calendar utime=Calendar.getInstance();
				utime.setTimeInMillis(json.getLong("update_time")*1000);
				entity.setPayed_time_loc(utime.getTime());
				entity.setReal_money(json.getDouble("real_price"));
				entity.setGood_desc(json.getString("desc"));
				int state=json.getInt("status");
				switch(state){
				case 0:
					entity.setState(OrderEntity.OrderState.PAY_ADD);
					break;
				case 1:
					entity.setState(OrderEntity.OrderState.PAY_WAIT);

					break;
				case 2:
					entity.setState(OrderEntity.OrderState.PAY_SUCCESS);

					break;
				case 3:
					entity.setState(OrderEntity.OrderState.PAY_FIN);

					break;
				case 4:
					entity.setState(OrderEntity.OrderState.PAY_CLOSE);
					break;
				}
				entity.setGood_name(json.getString("name"));
				adapter.add(entity);
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		adapter.notifyDataSetChanged();
	}
	
	private void check_orders() {
		dialog.setMessage(getString(R.string.loading_msg1));
		dialog.show();
		Map<String, String> params = new HashMap<String, String>();
		params.put("platform", String.valueOf(IConstant.PLATFORM));
		params.put("aid", AppUtils.aid);
		params.put("client_version", SystemUtil.getAppVersion(getActivity()));
		params.put("time", String.valueOf(Calendar.getInstance().getTimeInMillis()));
		params.put("channel", String.valueOf(AppUtils.channel));
		params.put("sign", HttpUtils.md5(params.get("aid") + params.get("time") + params.get("client_version")
				+ params.get("platform") + params.get("channel") + IConstant.NORMAL_MD5_KEY));
		params.put("ssign", HttpUtils.md5(params.get("aid") + params.get("time") + params.get("client_version")
				+ params.get("platform") + params.get("channel") + AppUtils.sKey));
		HttpUtils.post(new Handler() {

			@Override
			public void handleMessage(Message msg) {
				dialog.cancel();
				if (msg.what == HttpUtils.CODE_SUCCESS_RQ_100) {
					try {
						JSONObject json = new JSONObject(msg.obj.toString());
						if (json.getInt("code") == HttpUtils.RET_SUCCESS) {
							JSONArray orders = json.getJSONArray("orders");
							initUI(orders);
						} else {
							Toast toast = Toast.makeText(getActivity(), json.getString("msg"), Toast.LENGTH_LONG);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("", msg.obj.toString());
						Toast toast = Toast.makeText(getActivity(),
								getActivity().getResources().getString(R.string.server_format_error),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
				} else {
					Toast toast = Toast.makeText(getActivity(), ICodeMsg.ERROR_CODES_HTTP.get(msg.what),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
			}

		}, AppUtils.url + "/v/cRecharge/check_orders/", params);
	}
}
